package com.coocaa.x.uipackage.dialog;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.coocaa.x.app.framework.receiver.HomeKeyReceiver;
import com.coocaa.x.framework.app.CoocaaActivity;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.uipackage.R;
import com.coocaa.x.uipackage.SkinManager;
import com.coocaa.x.uipackage.ThemeDialog;
import com.coocaa.x.uipackage.widget.WaitingBar;

public class UpgradeDialog extends ThemeDialog implements OnClickListener, HomeKeyReceiver.IHomeKeyBroadcastListener {

    public static final int INSTALL_LOCATION_UNSPECIFIED = -1;
    public static final int INSTALL_LOCATION_AUTO = 0;
    public static final int INSTALL_LOCATION_INTERNAL_ONLY = 1;
    public static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;
    int contentWidth = CoocaaActivity.Div(1160);
    int contentHeight = CoocaaActivity.Div(700);
    int iconWidth = CoocaaActivity.Div(144);
    int ScrollY = 0;
    protected final int LINES_MAX = 5;
    private FrameLayout contentLayout;
    protected ImageView iconImage;
    protected TextView updateMsgView;
    protected LinearLayout textLayout;
    protected ImageView bgImage;
    protected ImageView scrollImage;
    protected Button updateButton;
    protected LinearLayout buttonLayout;
    protected Context mContext = null;
    protected FrameLayout mLayout = null;
    protected String applicationPath = null;
    protected int pageNoMargin;
    protected WaitingBar waitingBar = null;
    protected Bitmap waitingBitmap;
    private OnUpgradeDialogEventListener eventListener;

    public UpgradeDialog(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        LogUtils.d("super after");
        mContext = context;
        mLayout = new FrameLayout(context);
        initContentLayout();
        addBackgroundView();
        initTopLayout();
        addMainLayout();
        createScrollView();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(mLayout);
        getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        getWindow().getAttributes().dimAmount = 0.70f;
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    }

    /**
     * 注册button点击监听
     *
     * @param listener
     */
    public void setOnUpdateEventListener(OnUpgradeDialogEventListener listener) {
        eventListener = listener;
    }


    public void refreshUpdateMsg(String stupdateInfo, String apkPath) {
        hideChecking();
        if (apkPath == null || apkPath.equals("")) {
            updateMsgView.setText(R.string.updialog_latest_version);
            updateButton.setText(R.string.updialog_ok);
        } else {
            updateMsgView.setText(Html.fromHtml(stupdateInfo));
            updateButton.setText(R.string.updialog_update_now);
            applicationPath = apkPath;
        }
    }

    private void initContentLayout() {
        contentLayout = new FrameLayout(mContext);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(contentWidth, contentHeight, Gravity.CENTER);
        params.bottomMargin = iconWidth / 4;
        mLayout.addView(contentLayout, params);
    }

    private void addBackgroundView() {
        bgImage = new ImageView(mContext);
        bgImage.setId(123);
        SkinManager.getInstance().setBackgroundResource(bgImage, R.drawable.update_info_bg);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,//contentHeight - CoocaaActivity.iconWidth / 2, 
                Gravity.BOTTOM);
        params.topMargin = iconWidth / 2;
        contentLayout.addView(bgImage, params);
    }

    private void initTopLayout() {
        iconImage = new ImageView(mContext);
        iconImage.setBackgroundDrawable(mContext.getApplicationInfo().loadIcon(mContext.getPackageManager()));

        LinearLayout topLayout = new LinearLayout(mContext);
        topLayout.setPadding(CoocaaActivity.Div(60), 0, CoocaaActivity.Div(36), 0);
        topLayout.setGravity(Gravity.CENTER_VERTICAL);
        topLayout.addView(iconImage, new LayoutParams(iconWidth, iconWidth));

        FrameLayout.LayoutParams topParams = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, iconWidth, Gravity.TOP);
        contentLayout.addView(topLayout, topParams);
    }

    private void addMainLayout() {
        textLayout = new LinearLayout(mContext);
        int mainHeight = contentHeight - iconWidth - CoocaaActivity.Div(200);
        FrameLayout.LayoutParams mainParams = new FrameLayout.LayoutParams(contentWidth,
                mainHeight);
        mainParams.topMargin = iconWidth + CoocaaActivity.Div(50);

        updateMsgView = new TextView(mContext);
        updateMsgView.setTextSize(CoocaaActivity.Dpi(32));
        updateMsgView.setLineSpacing(0f, 1.5f);
        updateMsgView.setLines(LINES_MAX);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.leftMargin = iconWidth * 2 / 3;
        params.rightMargin = iconWidth * 2 / 3;
        textLayout.addView(updateMsgView, params);
        contentLayout.addView(textLayout, mainParams);

        buttonLayout = new LinearLayout(mContext);
        mainParams = new FrameLayout.LayoutParams(contentWidth,
                CoocaaActivity.Div(150), Gravity.BOTTOM);
        mainParams.topMargin = iconWidth + mainHeight;

        updateButton = new Button(mContext);
        updateButton.setBackgroundDrawable(SkinManager.getInstance().getDrawable(null, R.drawable.hot_seat_focus_bg));
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
                CoocaaActivity.Div(500), CoocaaActivity.Div(100));
        //buttonParams.bottomMargin = CoocaaActivity.Div(10);
        buttonParams.leftMargin = CoocaaActivity.Div(330);
        updateButton.setText(R.string.updialog_update_now);
        updateButton.setTextColor(Color.WHITE);
        updateButton.setTextSize(CoocaaActivity.Dpi(40));
        updateButton.setVisibility(View.VISIBLE);
        updateButton.setFocusable(true);
        updateButton.requestFocus();
        updateButton.setOnClickListener(this);
        buttonLayout.addView(updateButton, buttonParams);
        contentLayout.addView(buttonLayout, mainParams);

        waitingBar = new WaitingBar(mContext);
        SkinManager.getInstance().setBackgroundResource(waitingBar, R.drawable.dialog_waiting_bg);
        LinearLayout.LayoutParams waitingBarparams = new LinearLayout.LayoutParams(CoocaaActivity.Div(870), CoocaaActivity.Div(9));
        waitingBar.setLayoutParams(waitingBarparams);
        waitingBar.setSpeed(10);
        if (waitingBitmap == null)
            waitingBitmap = SkinManager.getInstance().getBitmap(null, R.drawable.dialog_waiting_front);
        waitingBar.setWaitingBitmap(waitingBitmap, CoocaaActivity.Div(60));
        mainParams = new FrameLayout.LayoutParams(CoocaaActivity.Div(870), CoocaaActivity.Div(9));
        mainParams.topMargin = iconWidth + CoocaaActivity.Div(200);
        mainParams.leftMargin = iconWidth * 2 / 3;
        contentLayout.addView(waitingBar, mainParams);
    }

    private void createScrollView() {
        pageNoMargin = iconWidth + CoocaaActivity.Div(65);
        scrollImage = new ImageView(mContext);
        SkinManager.getInstance().setBackgroundResource(scrollImage, R.drawable.gridview_scroll);
        FrameLayout.LayoutParams scrollParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LINES_MAX * updateMsgView.getLineHeight(), Gravity.RIGHT);
        scrollParams.topMargin = pageNoMargin;
        scrollParams.rightMargin = CoocaaActivity.Div(10);
        scrollImage.setVisibility(View.INVISIBLE);
        contentLayout.addView(scrollImage, scrollParams);

    }

    private void showChecking() {
        waitingBar.setVisibility(View.VISIBLE);
        waitingBar.startAnim();
        updateMsgView.setText(R.string.updialog_checking_upgrade);
        //scrollImage.setVisibility(View.INVISIBLE);
        updateButton.setVisibility(View.INVISIBLE);
    }

    private void hideChecking() {
        waitingBar.stopAnim();
        waitingBar.setVisibility(View.INVISIBLE);
        //scrollImage.setVisibility(View.VISIBLE);
        updateButton.setVisibility(View.VISIBLE);
        updateButton.setClickable(true);
    }

    Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {
            // TODO Auto-generated method stub
            super.dispatchMessage(msg);
            scrollImage.animate().alpha(0).setDuration(500);
        }

    };

    private void resetPageScroll(int textLines, int lineIndex) {
        int scrollY = 0;
        if (scrollImage.getVisibility() == View.INVISIBLE) {
            scrollImage.setVisibility(View.VISIBLE);
        }

        if (scrollImage.animate() != null)
            scrollImage.animate().cancel();

        FrameLayout.LayoutParams scrollParams = (FrameLayout.LayoutParams) scrollImage.getLayoutParams();
        int lineHeiget = updateMsgView.getLineHeight();
        if (textLines <= LINES_MAX) {
            scrollParams.height = LINES_MAX * lineHeiget;
        } else {
            float tempFloat = (float) LINES_MAX / ((float) textLines);
            scrollParams.height = (int) (tempFloat * LINES_MAX * lineHeiget);
        }

        scrollImage.setLayoutParams(scrollParams);

        if (textLines > LINES_MAX) {
            scrollY = (LINES_MAX * updateMsgView.getLineHeight() - scrollParams.height) / (textLines - 5);
        }

        scrollImage.animate().alpha(1).y(pageNoMargin + lineIndex * scrollY).setDuration(100);

        if (mHandler.hasMessages(1)) {
            mHandler.removeMessages(1);
        }
        //需要在handler里才起作用？
        mHandler.sendEmptyMessageDelayed(1, 100);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            if (ScrollY < (updateMsgView.getLineCount() - LINES_MAX)) {
                ScrollY = ScrollY + 1;
            }

            updateMsgView.setScrollY(ScrollY * updateMsgView.getLineHeight());
            resetPageScroll(updateMsgView.getLineCount(), ScrollY);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {

            if (ScrollY > 0) {
                ScrollY = ScrollY - 1;
            }
            updateMsgView.setScrollY(ScrollY * updateMsgView.getLineHeight());
            resetPageScroll(updateMsgView.getLineCount(), ScrollY);
            return true;
        }

        LogUtils.i("upgradeDialog", "ScrollY = " + ScrollY);
        return super.onKeyDown(keyCode, event);
    }

    private HomeKeyReceiver receiver = null;

    @Override
    public void dismiss() {
        // TODO Auto-generated method stub
        applicationPath = null;
        HomeKeyReceiver.destroy(mContext, receiver);
        super.dismiss();
    }

    @Override
    public void show() {
        // TODO Auto-generated method stub
        super.show();
        showChecking();
        receiver = HomeKeyReceiver.create(mContext);
        receiver.registerHomeKeyListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (eventListener != null) {
            eventListener.onClickCallBack(applicationPath);
        }
        dismiss();
    }

    @Override
    public void homeKeyReceiverCallBack() {
        // TODO Auto-generated method stub
        if (isShowing()) {
            dismiss();
        }
    }

    public interface OnUpgradeDialogEventListener {
        /**
         * 用户点击button回调
         */
        public void onClickCallBack(String apkFilePath);
    }

}
